﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Jewelnoid
{
    class SpriteObject : Object2D
    {
        public Rectangle sourceRect;
        public Vector2 spriteSize;
        public int currentFrame;
        public int totalFrames;
        public float fps;

        private double secondCount;

        public SpriteObject(Texture2D texture, Vector2 position, Vector2 spriteSize, Color color)
            : base(texture, position, color)
        {
            this.sourceRect = new Rectangle(0, 0, (int)spriteSize.X, (int)spriteSize.Y);
            this.spriteSize = spriteSize;

            currentFrame = 0;
            totalFrames = texture.Width / (int)spriteSize.X;
            secondCount = 0;
            fps = 1;

            this.position.X += this.texture.Width / 2 - this.sourceRect.Width / 2;
            this.position.Y += this.texture.Height / 2 - this.sourceRect.Height / 2;
        }

        public virtual void update(GameTime time)
        {
            this.sourceRect.X = currentFrame * (int)spriteSize.X;

            this.rect.Width = this.sourceRect.Width = (int)spriteSize.X;
            this.rect.Height = this.sourceRect.Height = (int)spriteSize.Y;

            updateRect();

            if (time.TotalGameTime.TotalSeconds - secondCount > 1f / fps)
            {
                secondCount = time.TotalGameTime.TotalSeconds;

                if (currentFrame < totalFrames - 1)
                {
                    currentFrame++;
                }
                else
                {
                    currentFrame = 0;
                }
            }
        }

        public override void updateRect()
        {
            this.rect.X = (int)this.position.X - this.texture.Width / 2;
            this.rect.Y = (int)this.position.Y - this.texture.Height / 2;
        }

        public override void draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(this.texture, this.position, this.sourceRect, this.color * alpha, this.rotation, this.pivot, this.scale, SpriteEffects.None, 0.5f);
            //spriteBatch.Draw(this.texture, this.rect, Color.Yellow);  //Desenha o retângulo de colisão.
        }
    }
}
